<template>
  <div class="ancnor">
    <p
      v-for="(item, index) in list"
      :key="index"
      :class="{ active: index === selectIndex }"
      @click="scrollIntoView(item.dom, index)"
    >
      {{ item.title }}
    </p>
  </div>
</template>
<script>
import { defineComponent, ref, onMounted, onUnmounted } from "vue";
import { debounce } from "lodash-es";

export default defineComponent({
  props: {
    offset: {
      type: Number,
      default: -120,
    },
  },
  setup(props) {
    const list = ref([]);
    const selectIndex = ref(0);
    const scrollIntoView = (dom, index) => {
      selectIndex.value = index;
      const { height } = getTop(dom);
      window.scrollTo({ top: height, behavior: "smooth" });
    };

    const getTop = (dom) => {
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      let body = document.body;
      let height = props.offset;
      let bridge = dom;
      do {
        height += bridge.offsetTop;
        bridge = bridge.offsetParent;
      } while (bridge !== body);
      return {
        height,
        relativePosition: height - scrollTop,
      };
    };
    const collectNode = () => {
      const listDom = document.querySelectorAll(".title");
      Array.from(listDom).forEach((item) => {
        console.dir(item);
        if (!item.dataset?.show) {
          list.value.push({
            title: item.innerText,
            dom: item,
          });
        }
      });
    };

    const scrollHandle = () => {
      list.value.find((item, index) => {
        const { relativePosition } = getTop(item.dom);
        if (relativePosition > props.offset) {
          selectIndex.value = index;
          return true;
        }
      });
    };
    const fn = debounce(scrollHandle, 100);

    onMounted(async () => {
      collectNode();
      window.addEventListener("scroll", fn);
    });

    onUnmounted(() => {
      window.removeEventListener("scroll", fn);
    });
    return { scrollIntoView, selectIndex, list };
  },
});
</script>
<style lang="scss" scoped>
.ancnor {
  // position: fixed;
  // top: calc(50% - 90px);
  // right: 24px;
  // z-index: 999;
  width: 100%;
  // padding: 4px 8px;
  cursor: pointer;
  background: #fff;
  // border-radius: 4px;
  // box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);

  .active {
    color: #28e;
    background: rgba(41, 164, 236, 0.08);
    position: relative;
  }
  .active:before {
    position: absolute;
    left: 0px;
    content: "";
    display: block;
    width: 4px;
    height: 40px;
    background-color: #00a0e9;
  }
  p {
    margin: 0;
    font-size: 16px;
    line-height: 40px;
    color: rgba(0, 0, 0, 0.3);
    padding: 0 20px;
  }
}
</style>
